var prefix = jsctx + "/enterpriseSubmemberApply";

var enterpriseSubmemberApply = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listPageSubmemberApply",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: true,
                pageSize: 20,
                pageList: [20],
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: (params.offset / params.limit) + 1,
                        submemberName: $("#submemberName").val().trim(),
                        mobile: $("#mobile").val().trim(),
                        enterpriseId:$("#enterpriseId").val()
                    };
                },
                columns: [
                    {
                        checkbox: true, field: '', width: '50', align: 'left',
                        formatter: function (value, row, index) {
                            if (row.applyStatus == '1') {
                                return {disabled: false}
                            } else {
                                return {disabled: true}
                            }
                        }
                    },
                    {
                        field: 'number',
                        title: '序号',
                        width: '50', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'submemberApplyId', title: '企业成员ID', align: 'left', width: '80'},
                    {field: 'nickname', title: '姓名', align: 'center', width: 80},
                    {field: 'recommenderId', title: '推荐人ID', align: 'center' ,width: 80},
                    {field: 'enterpriseName', title: '所属企业', align: 'center', width: 100},
                    {field: 'phone', title: '手机号', align: 'center', width: 100},

                   /* {
                        field: 'existUser', title: '是否管理员', width: '80', align: 'center',
                        formatter: function (value, row, index) {
                            if (value == true) {
                                return '是';
                            } else {
                                return '否';
                            }
                        }
                    },*/
                    {field: 'registerTime', title: '注册时间', align: 'center',width: 110},
                    {field: 'lastLoginTime', title: '最近登陆时间', align: 'center',width: 110},
                    {
                        field: 'status', title: '状态', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (row.applyStatus == '1') {
                                if (value == '0') {
                                    return  '<input class="tgl tgl-skewed" onclick="enterpriseSubmemberApply.switchStatus(' + row.submemberApplyId +',1 )" id="cb'+row.submemberApplyId+'" type="checkbox">' +
                                        '<label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.submemberApplyId+'"></label>'
                                } else {
                                    return '<input class="tgl tgl-skeweds"  onclick="enterpriseSubmemberApply.switchStatus(' + row.submemberApplyId +',0 )" id="cb'+row.submemberApplyId+'" type="checkbox">' +
                                        '<label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.submemberApplyId+'"></label>'
                                }
                            } else {
                                return null;
                            }

                        }
                    },
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        formatter: function (value, row, index) {
                            var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="审核" onclick="enterpriseSubmemberApply.showModel(\''
                                + row.submemberApplyId + '\')">审核</a> ';
                            var b = '<a class="btn btn-warning btn-sm ' + has_edit + '" href="#" mce_href="#" title="编辑" onclick="enterpriseSubmemberApply.editApply(\''
                                + row.submemberApplyId + '\')">编辑</a> ';
                            var c = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="编辑" onclick="enterpriseSubmemberApply.detailApply(\''
                                + row.submemberApplyId + '\')">详情</a> ';
                            var d = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="删除" onclick="enterpriseSubmemberApply.deleteApply(\''
                                + row.submemberApplyId
                                + '\')">删除</a> ';
                            var operate = '';
                            if (row.applyStatus == '0') {
                                operate = operate + a;
                            }
                            operate = operate + b + c ;
                            operate = operate + d;

                            return operate;
                        }
                    }
                ]
            });
    };

    function switchStatus (isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/updateSubmemberApplyStatus",
            data: {
                status: state,
                id:isId
            },
            success: function (data) {
                reLoad();
            },
            error: function (xhr, error, exception) {
                let errorMsg = xhr.responseText;
                openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
            }
        });
    }

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                enterpriseName: $("#enterpriseName").val(),
                mobile: $("#mobile").val(),
                enterpriseId:$("#enterpriseId").val(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    function initSwitch() {
        $("[name='submember-status']").bootstrapSwitch({
            onText: "启用",      // 设置ON文本
            offText: "禁用",    // 设置OFF文本
            onColor: "primary",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size: "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            hadleWidth: "30",
            // 当开关状态改变时触发
            onSwitchChange: function (event, state) {
                //修改操作
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: prefix + "/updateSubmemberApplyStatus",
                    data: {
                        status: state ? 0 : 1,
                        id: this.value
                    },
                    success: function (data) {
                        $('#TestTables').bootstrapTable('refresh'); //Table页面刷新
                    },
                    error: function (xhr, error, exception) {
                        let errorMsg = xhr.responseText;
                        openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
                    }
                });
            }
        })
    }

    function applyRecord(submemberApplyId) {
        location.href = prefix + "/applyRecord/" + submemberApplyId;
    }

    /*  模态框  */
    function showModel(id) {
        $('#exampleModal').modal('show');

        $("#submitButton").unbind("click").bind("click", function () {
            $.ajax({
                url: prefix + "/updateSubmemberApplyForAudit",
                type: "post",
                data: {
                    "id": id,
                    "status": $("#status").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        // $('#exampleModal').on('hidden.bs.modal', function () {
                        //     document.getElementById("contentForm").reset();
                        // })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        // $('#exampleModal').on('hidden.bs.modal', function () {
                        //     document.getElementById("contentForm").reset();
                        // })
                        $('#exampleModal').modal('hide')
                    }
                }
            })
        })

    }

    function editApply(applyId) {
        location.href = prefix + "/edit/" + applyId;
    }

    function add() {
        location.href = prefix + "/add";
    }

    function detailApply(applyId) {
        location.href = prefix + "/detail/" + applyId;
    }

    function deleteApply(applyId) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteSubmemberApply",
                type: "post",
                data: {
                    'id': applyId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function batchHandleRows() {
        var rows = $("#exampleTable").bootstrapTable('getSelections');
        if (rows.length == 0) {
            alert("请先选择要设置的记录!");
            return;
        } else {
            var idList = new Array();
            $(rows).each(function () {
                if (this.submemberApplyId != null){
                    idList.push(this.submemberApplyId);
                }
            });
            layer.open({
                type: 1,
                title: '转渠道商确认',
                closeBtn: false,
                shade: 0.4,
                shift: 7,
                shadeClose: true,
                content: $("#open-main"),
                btn: ['确定', '取消'],
                yes: function (index) {//点击确定回调
                    layer.close(index);
                    $.ajax({
                        url: jsctx + "/enterpriseSubmember/updateSubmemberToChannel",
                        type: "post",
                        data: {
                            idList: idList,
                        },
                        traditional:true,
                        success: function (data) {
                            layer.close(index);
                            if (data.status == 200) {
                                reLoad();
                                layer.msg(data.message);
                            } else {
                                layer.msg(data.message);
                            }
                        }
                    });
                },
            });
        }
    }

    return {
        init: init,
        reLoad: reLoad,
        applyRecord: applyRecord,
        showModel: showModel,
        editApply: editApply,
        detailApply: detailApply,
        deleteApply:deleteApply,
        exportList:exportList,
        add:add,
        batchHandleRows: batchHandleRows,
        switchStatus:switchStatus
    };
})();


var saveApplyRecord = (function () {
    function init() {

        validateRule();
    };

    function save() {
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/updateSubmemberApply",
            data: $('#frm').serialize(),
            async: false,
            error: function (request) {
                parent.layer.alert("请重新登录");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600 || data.status == 601) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                nickname: {
                    required: true
                },phone: {
                    required: true
                }
            },
            messages: {
                nickname: {
                    required: icon + "请输入成员名称"
                },phone: {
                    required: icon + "请输入手机号"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };

    return {
        init: init
    };
})();

var addEnterpriseSubmemberApply = (function () {
    function init() {

        validateRule();
    };

    function save() {
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/addSubmemberApply",
            data: $('#frm').serialize(),
            async: false,
            error: function (request) {
                parent.layer.alert("失败");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600 || data.status == 601) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                nickname: {
                    required: true
                },phone: {
                    required: true
                }
            },
            messages: {
                nickname: {
                    required: icon + "请输入成员名称"
                },phone: {
                    required: icon + "请输入手机号"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };

    return {
        init: init
    };
})();

